#!/bin/sh
set -e

echo() { printf %s\\n "$*"; }  # depends on standard IFS (which we have)

BUILD="$(pwd)"
newline="
"

if test -f "$BUILD"/ffmpeg_options ; then
    IFS=$newline
    set -- $(cat "$BUILD"/ffmpeg_options) "$@"
    unset -v IFS
fi

OPTIONS="--enable-gpl --disable-debug --disable-doc --enable-static --disable-shared"
if "$BUILD"/scripts/test-libmpv ; then
    OPTIONS="$OPTIONS --enable-pic"
fi

# Do FFmpeg's job.
if ( echo "$OPTIONS" "$@" | \
     grep -q -E -e "-openssl|-gnutls|-mbedtls|-libtls|-schannel|-securetransport" )
then
    echo TLS/SSL user option specified, skipping autodetection
else
    if pkg-config gnutls ; then
        OPTIONS="$OPTIONS --enable-gnutls"
        echo "Auto-enabling GnuTLS."
    elif pkg-config openssl ; then
        OPTIONS="$OPTIONS --enable-nonfree --enable-openssl"
        echo "Auto-enabling OpenSSL (creates a non-redistributable binary)."
    fi
fi

case "$PKG_CONFIG_PATH" in
  '')
    export PKG_CONFIG_PATH="$BUILD/build_libs/lib/pkgconfig"
    ;;
  *)
    export PKG_CONFIG_PATH="$BUILD/build_libs/lib/pkgconfig:$PKG_CONFIG_PATH"
    ;;
esac

echo Using ffmpeg options: $OPTIONS "$@"

mkdir -p "$BUILD"/ffmpeg_build
cd "$BUILD"/ffmpeg_build
# need to link against stdc++ in case libplacebo was built with glslang,
# which requires that
export LDFLAGS="$LDFLAGS -lstdc++"
"$BUILD"/ffmpeg/configure --prefix="$BUILD"/build_libs $OPTIONS "$@"
